package com.wyg.blog.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;

/**
 * @description:
 * @author: WYG
 * @time: 2020/6/21 22:35
 */

public class JwtTokenUtil {

    //过期时间
    private static final long EXPIRATION_TIME = 3600000L * 24;


    public static String generateToken(String username,PrivateKey privateKey){
        Map<String,Object> claims = new HashMap<>(1);
        claims.put(Claims.SUBJECT, username);
        claims.put(Claims.ISSUED_AT, new Date());
        return generateToken(claims,privateKey);
    }

    private static String createJTI() {
        return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
    }

    public static String getUsernameFromToken(String token, PublicKey publicKey){
        System.out.println("开始解析用户名");
        Jws<Claims> jws = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token);
        Claims claims = jws.getBody();
        System.out.println("获得claims"+claims);
        String username = claims.getSubject();
        return username;
    }

    public static Boolean isTokenExpired(String token, PublicKey publicKey) throws JwtException{
        try{
            Jws<Claims> jws = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token);
            Claims claims = jws.getBody();
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        }catch (JwtException e){
            new Throwable(e);
        }
        return true;
    }

    public static String refreshToken(String token, PrivateKey privateKey, PublicKey publicKey){
        StringBuffer refreshToken = new StringBuffer();
        try{
            Jws<Claims> jws = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token);
            Claims claims = jws.getBody();
            claims.put(Claims.ISSUED_AT, new Date());
            refreshToken.append(generateToken(claims,privateKey));
        }catch (JwtException e){
            System.out.println(e.getMessage());
        }
        return refreshToken.toString();
    }

    public static Boolean validate(String token, String username, PublicKey publicKey){
        String name = getUsernameFromToken(token, publicKey);
        return username.equals(name) && !isTokenExpired(token, publicKey);
    }

    public static String generateToken(Map<String, Object> claims, PrivateKey privateKey){
        Date expiration = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        return Jwts.builder()
                .setIssuer("wyg")
                .setClaims(claims)
                .setExpiration(expiration)
                .setId(createJTI())
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }

}
